<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/7/23
 * Time: 13:37
 */

namespace app\admin\controller;

use think\Db;
use think\Request;

class Goods extends Base
{
    /**
     * 消息首页展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [
                'good_status' => ['<>',3]
            ];
            //状态
            if(isset($params['n_range']) && $params['n_range'] != ''){
                if($params['n_range'] == 3){
                    $where['good_status'] = 1;
                    $where['good_stock'] = ['<=',0];
                }else{
                    $where['good_status'] = $params['n_range'];
                }

            }
            // 名字
            if(isset($params['n_title']) && $params['n_title'] != ''){
                $where['good_name|school_name'] = ['like', '%' . $params['n_title'] . '%'];
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'g.*,school_name,school_id';
            $count = Db::table('up_self_goods')->alias('g')
                ->join('up_school s','g.good_school=s.school_id','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_self_goods')->alias('g')
                ->join('up_school s','g.good_school=s.school_id','LEFT')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('good_sort asc,good_update_time desc')
                ->field($field)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    /**
     * 改状态
     * @author
     */
    public function changeGoodStatus()
    {
        extract(input());
        $res = Db::table('up_self_goods')
            ->where('good_id',$id)
            ->update([
                'good_update_time' => date('Y-m-d H:i:s'),
                'good_status' => $num
            ]);
        if($res){
            return json(['code' => 200, 'msg' => '成功']);
        }else{
            return json(['code' => 100, 'msg' => '失败']);
        }
    }

    /**
     * 排序编辑
     * @return mixed|\think\response\Json
     */
    public function updateSort(){
        $id = input('id');
        $param = [
            'good_sort'=>input('value'),
        ];
        $res = Db::name('self_goods')->where('good_id',$id)->update($param);
        if($res){
            return json(['code' => 200, 'msg' => '修改成功']);
        }else{
            return json(['code' => 100, 'msg' =>' 修改失败']);
        }
    }


    /**
     * 发布商品
     * @return mixed|\think\response\Json
     */
    public function goodAdd(){
        if(Request::instance()->isPost()){
            Db::startTrans();
            try{
                $params = input('param.');
                $time = date('Y-m-d H:i:s');
                $gg_json = json_decode($params['gg_json'],true);
                $data = [
                    'good_name' => trim($params['good_name'], ' '), // 标题
                    'good_price' => round($params['good_price'], 2),// 内容
                    'good_thumb' => $params['good_thumb'],// 内容
                    'good_image' => $params['good_image'],// 内容
                    'good_status' => $params['good_status'],// 内容
                    'good_stock' => 0,// 内容
                    'good_content' => $params['content'],// 内容
                    'good_school' => $params['good_school'],// 内容
                    'good_guige' => json_encode($gg_json),// 内容
                    'good_create_time' => $time, // 推送时间
                    'good_update_time' => $time, // 推送时间
                ];
                $goods_id = Db::table('up_self_goods')->insertGetId($data);
                //attrs
                $attrs = trim($params['attr_json'],'|||');
                $attr_arr = explode('|||',$attrs);
                $rightStore = 0;
                foreach ($attr_arr as $k=>$v){
                    $v_arr = explode('___',$v);
                    $attr_insert = [
                        'goods_id' => $goods_id,
                        'sign_str' => $v_arr[0],
                        'sign_id' => $v_arr[1],
                        'price' => round($v_arr[2],2),
                        'stock' => (int)$v_arr[3],
                        'no' => $v_arr[4],
                        'weight' => $v_arr[5],
                        'pic_url' => $v_arr[6],
                    ];
                    Db::table('up_self_goods_attr')->insert($attr_insert);
                    $rightStore += (int)$v_arr[3];
                }
                if($rightStore > 0){
                    Db::table('up_self_goods')->where('good_id',$goods_id)->setField('good_stock',$rightStore);
                }
                Db::commit();
                return json(['code' => 200, 'msg' => '发布成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '发布失败']);
            }
        }
        //所有学校
        $school = Db::table('up_school')
            ->field('school_id, school_name')
            ->select();
        $this->assign([
            'school' => $school
        ]);
        return $this->fetch('goods/goodadd');
    }
    /**
     * 编辑商品
     * @return mixed|\think\response\Json
     */
    public function goodEdit(){
        if(Request::instance()->isPost()){
            Db::startTrans();
            try{
                $params = input('param.');
                $time = date('Y-m-d H:i:s');
                $gg_json = json_decode($params['gg_json'],true);
                $data = [
                    'good_name' => trim($params['good_name'], ' '), // 标题
                    'good_price' => round($params['good_price'], 2),// 内容
                    'good_thumb' => $params['good_thumb'],// 内容
                    'good_image' => $params['good_image'],// 内容
                    'good_status' => $params['good_status'],// 内容
                    'good_stock' => 0,// 内容
                    'good_content' => $params['content'],// 内容
                    'good_school' => $params['good_school'],// 内容
                    'good_guige' => json_encode($gg_json),// 内容
                    'good_update_time' => $time, // 推送时间
                ];
                $goods_id = $params['good_id'];
                $havechange = $params['havechange'];
                Db::table('up_self_goods')->where('good_id',$goods_id)->update($data);
                $rightStore = 0;
                //attrs
                $attrs = trim($params['attr_json'],'|||');
                $attr_arr = explode('|||',$attrs);
                if($havechange == 1){
                    foreach ($attr_arr as $k=>$v){
                        $v_arr = explode('___',$v);
                        $attr_insert = [
                            'goods_id' => $goods_id,
                            'sign_str' => $v_arr[0],
                            'sign_id' => $v_arr[1],
                            'price' => round($v_arr[2],2),
                            'stock' => (int)$v_arr[3],
                            'no' => $v_arr[4],
                            'weight' => $v_arr[5],
                            'pic_url' => $v_arr[6],
                        ];
                        Db::table('up_self_goods_attr')
                            ->where('goods_id',$goods_id)
                            ->where('sign_id',$v_arr[1])
                            ->where('is_delete',0)
                            ->update($attr_insert);
                        $rightStore += (int)$v_arr[3];
                    }
                }else{
                    Db::table('up_self_goods_attr')
                        ->where('goods_id',$goods_id)
                        ->setField('is_delete',1);
                    foreach ($attr_arr as $k=>$v){
                        $v_arr = explode('___',$v);
                        $attr_insert = [
                            'goods_id' => $goods_id,
                            'sign_str' => $v_arr[0],
                            'sign_id' => $v_arr[1],
                            'price' => round($v_arr[2],2),
                            'stock' => (int)$v_arr[3],
                            'no' => $v_arr[4],
                            'weight' => $v_arr[5],
                            'pic_url' => $v_arr[6],
                        ];
                        Db::table('up_self_goods_attr')->insert($attr_insert);
                        $rightStore += (int)$v_arr[3];
                    }
                }
                if($rightStore > 0){
                    Db::table('up_self_goods')->where('good_id',$goods_id)->setField('good_stock',$rightStore);
                }
                Db::commit();
                return json(['code' => 200, 'msg' => '更新成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '更新失败']);
            }
        }
        $g_id = input('good_id');
        $data = Db::table('up_self_goods')
            ->where('good_id',$g_id)
            ->find();
        //所有学校
        $school = Db::table('up_school')
            ->field('school_id, school_name')
            ->select();
        $guige = json_decode($data['good_guige'],true);
        $atrrs = Db::table('up_self_goods_attr')
            ->where('goods_id',$g_id)
            ->where('is_delete',0)
            ->select();
        $temp_key = array_column($atrrs,'sign_id');
        $attr_arr = array_combine($temp_key,$atrrs) ;
        $this->assign([
            'school' => $school,
            'data' => $data,
            'guige' => $guige,
            'atrrs' => json_encode($attr_arr)
        ]);
        return $this->fetch('goods/goodedit');
    }
    
    /**
     * 商品详情
     * @return mixed
     */
    public function goodInfo(){
        $g_id = input('good_id');
        $data = Db::table('up_self_goods')
            ->where('good_id',$g_id)
            ->find();
        //所有学校
        $school = Db::table('up_school')
            ->field('school_id, school_name')
            ->select();
        $guige = json_decode($data['good_guige'],true);
        $atrrs = Db::table('up_self_goods_attr')
            ->where('goods_id',$g_id)
            ->where('is_delete',0)
            ->select();
        $temp_key = array_column($atrrs,'sign_id');
        $attr_arr = array_combine($temp_key,$atrrs) ;
        $this->assign([
            'school' => $school,
            'data' => $data,
            'guige' => $guige,
            'atrrs' => json_encode($attr_arr)
        ]);
        return $this->fetch('goods/goodinfo');
    }
    

    /**
     * 删除商品
     * @return \think\response\Json
     */
    public function goodDel(){
        $g_id = input('id');
        $res = Db::table('up_self_goods')->where('good_id',$g_id)->setField('good_status',3);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    /**
     * 查看评价
     * @return mixed|\think\response\Json
     */
    public function goodsComments(){
        if(request()->isAjax()){
            extract(input());
            $good_id = input('good_id');
            $where = [
                'comment_good_id' => $good_id
            ];
            $count = Db::name('self_goods_comment')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.comment_user_id','left')
                ->join('up_self_goods g','a.comment_good_id=g.good_id','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('self_goods_comment')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.comment_user_id','left')
                ->join('up_self_goods g','a.comment_good_id=g.good_id','LEFT')
                ->where($where)
                ->field('a.*,uuu.user_username,uuu.user_phone,good_name')
                ->select();
            if($lists){
                foreach ($lists as $k=>$v){
                    if($v['comment_image']){
                        $lists[$k]['comment_image'] = explode(',',$v['comment_image']);
                    }
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $good_id = input('good_id');
        $this->assign('good_id',$good_id);
        return $this->fetch('goods/goodscomments');
    }
    /**
     * 批量导出（待定，之前的消息导出）
     * @return \think\response\Json
     */
    public function excelOut(){
        $ids = input('ids');
        if($ids == ''){
            return json(['code' => 100, 'msg' => '请选择需要导出的消息']);
        }
        $where['n_id'] = array('IN',$ids);
        $lists = Db::name('notice')
            ->where($where)
            ->field('n_id, n_title, n_content, n_range, n_send_datetime')
            ->order('n_send_datetime desc')
            ->select();
        
        foreach($lists as $key => $vo){
            //状态
            if($vo['n_range'] == 1) $lists[$key]['n_range'] = '全部';
            if($vo['n_range'] == 2) $lists[$key]['n_range'] = '个别';
        }
        
        $cellname = [
            ['n_id','消息ID',10,'LEFT'],
            ['n_title','推送标题',40,'LEFT'],
            ['n_content','推送内容',80,'LEFT'],
            ['n_range','推送人群',20,'LEFT'],
            ['n_send_datetime','推送时间',20,'LEFT'],
        ];
        $res = exportExcel('系统消息列表','Notice',$cellname,$lists);
        return json($res);
    }
}